package com.qf.springbootproject.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.springbootproject.user.entity.Users;
import com.qf.springbootproject.user.mapper.UsersMapper;
import com.qf.springbootproject.user.service.UsersService;
import com.qf.springbootproject.utils.ResultVo;
import com.qf.springbootproject.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author yangyeqi
 * @since 2023-02-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    /*
     * 注册
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo register(String username, String password) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", username);
        Users user = getOne(usersQueryWrapper);
        Users users = new Users();
        if (user == null) {
            //注册时先生成随机盐字符串
            String salt = SaltUtils.getSalt(8);
            //设置salt到user对象
            users.setSalt(salt);
            //生成加密密码
            //创建shiro创建的加密对象
            //参数1 原密码 2 盐 3 hash次数
            Md5Hash md5Hash = new Md5Hash(password, salt, 1024);
            String sercetPwd = md5Hash.toHex();
            users.setPassword(sercetPwd);
            users.setUsername(username);
            users.setSalt(salt);
            save(users);//保存到数据库
            return ResultVo.ok(users);
        } else {
            return ResultVo.error();
        }
    }


}
